﻿using System.IO.Ports;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Wpf.Ui.Appearance;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow 
    {

        public SerialPort serialPort;

        public MainWindow()
        {
            InitializeComponent();
            ApplicationThemeManager.Apply(this);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            serialPort = new SerialPort();
            string[] names = SerialPort.GetPortNames();

            serialPort.PortName = "COM2";
            serialPort.Parity=Parity.None;
            serialPort.BaudRate=9600;
            serialPort.DataBits=8;
            serialPort.StopBits=StopBits.One;

            serialPort.Open();
            serialPort.Write("hello");

            //byte[] bytes = new byte[5];
            //serialPort.Read(bytes,0,bytes.Length);
            //string readStr = Encoding.ASCII.GetString(bytes);

            serialPort.DataReceived+=(sender, e) =>
            {
                byte[] bytes = new byte[5];
                (sender as SerialPort).Read(bytes, 0, bytes.Length);
                string readStr = Encoding.ASCII.GetString(bytes);
                
            };

            Console.WriteLine();


        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //AddressFamily family = AddressFamily.InterNetwork;
            //Socket socket = new Socket(family,SocketType.Stream,ProtocolType.Tcp);
            ////Socket socket = new Socket(family, SocketType.Dgram, ProtocolType.Udp);
            ////socket.Bind(new IPEndPoint(IPAddress.Any,9999));
            ////socket.Listen();
            //socket.Connect("192.168.0.1",502);  //TCP三次握手

            ////socket.Send();
            ////socket.Receive();
            //TcpClient tcpClient = new TcpClient();
            //TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 502));
            //listener.AcceptSocket();

            TcpServerTest();

        }


        private void TcpServerTest() {

            Dictionary<EndPoint, Socket> clients = new Dictionary<EndPoint, Socket>();

            AddressFamily family = AddressFamily.InterNetwork;
            Socket server = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
            server.Bind(new IPEndPoint(IPAddress.Any,8080));
            server.Listen();

            //while (true) {
            //    var client = server.Accept();
            //    clients.Add(client.RemoteEndPoint, client);
            //    Task.Run(() =>
            //    {
            //        while (true)
            //        {
            //            byte[] bytes = new byte[1024];
            //            client.Receive(bytes);
            //            var acceptStr = Encoding.ASCII.GetString(bytes);
            //            Console.WriteLine(acceptStr);
            //        }
            //    });
            //}
            server.BeginAccept(ServerAccept, server);

        }

        private void ServerAccept(IAsyncResult result) {
            var server = result.AsyncState as Socket;

            var client = server.EndAccept(result);
            byte[] bytes = new byte[1024];

            TcpReceive tcpReceive = new TcpReceive
            {
                Datas = bytes,
                Socket = client
            };

            string connectMsg = "服务器返回:连接成功！";
            client.Send(Encoding.UTF8.GetBytes(connectMsg));
            client.BeginReceive(bytes,0, bytes.Length,SocketFlags.None, ClientRecevie, tcpReceive);

            server.BeginAccept(ServerAccept,server);
        }

        private void ClientRecevie(IAsyncResult result) {
            var tr = result.AsyncState as TcpReceive;
            int len = tr.Socket.EndReceive(result);
            if (len==0) {
                tr.Socket.Shutdown(SocketShutdown.Both);
                tr.Socket.Close();
                return;
            }

            var acceptStr = Encoding.UTF8.GetString(tr.Datas);

            tr.Socket.BeginReceive(tr.Datas, 0, tr.Datas.Length, SocketFlags.None, ClientRecevie, tr);
        }


        class TcpReceive { 
            public byte[] Datas { get; set; }

            public Socket Socket { get; set; }
        }


        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            TcpClientTest();
        }

        private void TcpClientTest()
        {
            AddressFamily family = AddressFamily.InterNetwork;
            Socket client = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
            client.Connect("192.168.5.90",8080);
            if (client.Connected) {
                //string connectMsg = "客户端发送的消息:发送的第一条消息！";
                //client.Send(Encoding.UTF8.GetBytes(connectMsg));
                string connectMsg = "客户端发送的消息:发送的第一条消息！";
                byte[] data = Encoding.UTF8.GetBytes(connectMsg);
                client.BeginSend(data,0, data.Length,SocketFlags.None,ClientSendCallback,client);

            }

        }

        private void ClientSendCallback(IAsyncResult result)
        {
            var client = result.AsyncState as Socket;
            var len = client.EndSend(result);
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}